package com.zhihuichongcheng.application.ui.cricle.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.smartlib.cmnObject.dialog.DialogOnClick;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.LogUtil;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.cricle.CricleImageInfo;
import com.zhihuichongcheng.application.constant.Constants;
import com.zhihuichongcheng.application.widget.photoview.CirclePhotoView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by 3water on 2016/11/5.
 */

public class ShowImageActivity extends BaseActivity {
    public static final String EXTRA_BOOLEAN_SHOW_DEL_BTN = "extra_show_del";
    public static final String EXTRA_RESULT_IMGS = "extra_result_imgs";

    private CirclePhotoView myZoomImageView;
    private ViewPager viewPager;
    private ArrayList<CricleImageInfo> mListData = new ArrayList<>();
    private int mIndex;
    private ImagePageAdapter mAdapter;
    private LinearLayout mLlBottom;
    private boolean showDelBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != getIntent().getExtras()) {
            Bundle bundle = getIntent().getExtras();
            if (bundle.containsKey(EXTRA_BOOLEAN_SHOW_DEL_BTN))
                showDelBtn = bundle.getBoolean(EXTRA_BOOLEAN_SHOW_DEL_BTN, false);
        }
        setContentView(R.layout.activity_show_img);
        initView();
        initDate();
    }

    private void initView() {
        viewPager = (ViewPager) findViewById(R.id.vp_image);
        mAdapter = new ImagePageAdapter();
        mLlBottom = (LinearLayout) findViewById(R.id.ll_bottom);
        if (showDelBtn)
        setTvRight("删除", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mAdapter.showDeleteDialog(mIndex);
            }
        });
    }

    private void initDate() {
        Intent intent = getIntent();
        if (intent != null) {
            if (intent.hasExtra("index")) {
                mIndex = intent.getIntExtra("index", -1);
            }
            if (intent.hasExtra("list")) {
                mListData = intent.getParcelableArrayListExtra("list");
            }
        }
        viewPager.setOffscreenPageLimit(mListData.size());
        viewPager.setAdapter(mAdapter);
        viewPager.setCurrentItem(mIndex, false);
        initPoint();
        setIndexPoint(mIndex);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setIndexPoint(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    private void initPoint() {
        mLlBottom.removeAllViews();
        for (int i = 0; i < mListData.size(); i++) {
            ImageView view = new ImageView(mContext);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(10, 0, 10, 0);
            params.gravity = Gravity.CENTER;
            view.setLayoutParams(params);
            view.setBackgroundResource(R.drawable.ic_main_point_normal);
            mLlBottom.addView(view);
        }
    }

    private void setIndexPoint(int index) {
        setTitle(index + 1 + "/" + mListData.size());
        for (int i = 0; i < mLlBottom.getChildCount(); i++) {
            View view = mLlBottom.getChildAt(i);
            if (i == index) {
                view.setBackgroundResource(R.drawable.ic_main_point_selected);
            } else {
                view.setBackgroundResource(R.drawable.ic_main_point_normal);
            }
        }
    }

    private File saveImage(Bitmap bitmap, String path) {
        String paths[] = path.split("/");
        if (paths.length > 0) {
            LogUtil.logI(paths[paths.length - 1]);
        }
        File file = new File(Constants.Const_Cache_Dir + "/" + paths[paths.length - 1]);
        try {
            BufferedOutputStream
                    bos = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            mContext.sendBroadcast(intent);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    @Override
    protected void onFinished() {
        super.onFinished();
        if (showDelBtn) {
            Intent intent = new Intent();
            intent.putParcelableArrayListExtra(EXTRA_RESULT_IMGS, mListData);
            setResult(RESULT_OK, intent);
        }
    }

    class ImagePageAdapter extends PagerAdapter {
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            //这个方法用来实例化页卡
            View view = LayoutInflater.from(mContext).inflate(R.layout.fragment_show_image, null);
            final CirclePhotoView photoView = (CirclePhotoView) view.findViewById(R.id.im_image);
            //final CriclePhotoView view = new CriclePhotoView(mContext);
            final CricleImageInfo info = mListData.get(position);
            photoView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            photoView.enable();
            photoView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (photoView.getScal() == 1) {
                        finish();
                    }
                }
            });
            photoView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View view) {
                    showSaveDialog(photoView, info);
                    return false;
                }
            });
            Glide.with(mContext).load(info.getJinbaoHomeImgUrl()).placeholder(R.drawable.ic_cricle_defalut_avatar).into(photoView);
            container.addView(view, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));//添加页卡
            return view;
        }

        private void showSaveDialog(final CirclePhotoView photoView, final CricleImageInfo info) {
            DialogUtil.showSimpleAlertDialog(mContext, new DialogOnClick() {
                @Override
                public void onClick(Object o) {
                    Bitmap bitmap = getViewBitmap(photoView);
                    File file = saveImage(bitmap, info.getJinbaoHomeImgUrl());

                }
            }, "保存到相册");
        }

        private Bitmap getViewBitmap(View v) {
            v.clearFocus();
            v.setPressed(false);
            boolean willNotCache = v.willNotCacheDrawing();
            v.setWillNotCacheDrawing(false);
            // Reset the drawing cache background color to fully transparent
            // for the duration of this operation
            int color = v.getDrawingCacheBackgroundColor();
            v.setDrawingCacheBackgroundColor(0);
            if (color != 0) {
                v.destroyDrawingCache();
            }
            v.buildDrawingCache();
            Bitmap cacheBitmap = v.getDrawingCache();
            if (cacheBitmap == null) {
                return null;
            }

            Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

            // Restore the view
            v.destroyDrawingCache();
            v.setWillNotCacheDrawing(willNotCache);
            v.setDrawingCacheBackgroundColor(color);
            /***
             *
             */
            return bitmap;
        }

        public void showDeleteDialog(final int position) {
            if (position >= 0)
                DialogUtil.showSimpleAlertDialog(mContext, new DialogOnClick() {
                    @Override
                    public void onClick(Object o) {
                        if (mAdapter.getCount() == 1) {
                            Intent intent = new Intent();
                            intent.putParcelableArrayListExtra(EXTRA_RESULT_IMGS, null);
                            setResult(RESULT_OK, intent);
                            finish();
                            return;
                        }
                        mListData.remove(position);
                        mAdapter.notifyDataSetChanged();
                        setIndexPoint(Math.max(mIndex - 1, 0));
                        initPoint();
                    }
                }, "删除");
        }

        @Override
        public int getCount() {
            return mListData.size();//返回页卡的数量
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;//官方提示这样写
        }
    }
}
